<template>
    <div id="app">
        <el-card shadow="always">
            <h1>学生管理系统</h1>
            <el-divider></el-divider>
            <!--1. 条件查询表单-->
            <el-form :inline="true" :model="studentSearch" class="demo-form-inline" align="left" size="small">
                <el-form-item>
                    <el-input v-model="studentSearch.sname" placeholder="学生姓名"/>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="studentSearch.addr" placeholder="学生住址"/>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="studentSearch.cid" placeholder="所在班级">
                        <el-option label="所有班级" value="0"></el-option>
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="search" plain>搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" icon="el-icon-plus" @click="addStud" plain>添加学生</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="warning" icon="el-icon-milk-tea" @click="handleDelete" plain>批量删除</el-button>
                </el-form-item>
            </el-form>
            <el-table
                    :data="studList"
                    stripe
                    style="width: 100%"
                    @selection-change="handleSelectionChange">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column
                        label="学号"
                        align="center"
                        prop="sid"/>
                <el-table-column
                        label="姓名"
                        align="center"
                        prop="sname"/>
                <el-table-column
                        label="性别"
                        align="center"
                        prop="sex"/>
                <el-table-column
                        label="年龄"
                        align="center"
                        prop="age"/>
                <el-table-column
                        label="住址"
                        align="center"
                        prop="addr"/>
                <el-table-column
                        label="班级名称"
                        align="center"
                        prop="cname"/>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button-group>
                            <el-button
                                    size="mini"
                                    type="success"
                                    @click="handleEdit(scope.row)" icon="el-icon-edit">
                            </el-button>
                            <el-button
                                    size="mini"
                                    type="danger"
                                    @click="handleDelete(scope.row)" icon="el-icon-delete">
                            </el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    align="right"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
            <!--编辑学生的对话框-->
            <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
                <el-form :model="student" align="left">
                    <el-form-item label="学生姓名" :label-width="formLabelWidth">
                        <el-input v-model="student.sname" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="学生性别" :label-width="formLabelWidth" align="left">
                        <el-radio v-model="student.sex" label="男">男</el-radio>
                        <el-radio v-model="student.sex" label="女">女</el-radio>
                    </el-form-item>
                    <el-form-item label="学生年龄" :label-width="formLabelWidth">
                        <el-input v-model="student.age" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="学生住址" :label-width="formLabelWidth">
                        <el-input v-model="student.addr" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="所在班级" :label-width="formLabelWidth" align="left">
                        <el-select v-model="student.cid" placeholder="请选择所在班级">
                            <el-option :label="c.cname" :value="c.cid" v-for="c in classes"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="save()">确 定</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>
<script>
    // 1. 引入学生管理模块
    import studentApi from '@/api/student'
    import classesApi from '@/api/classes'

    export default {
        data() {
            return {
                studList: [],
                page: 1,         // 当前页
                pageSize: 5,     // 每页大小
                total: 100,     // 总记录数
                studentSearch: {},  // 条件查询对象
                classes: [],     // 所有班级列表
                dialogFormVisible: false,        // 是否显示对话框
                formLabelWidth: '100px',         // 表单控件前面文本的宽度
                student: {},     // 添加或修改的学生对象
                title: '添加学生',
                multipleSelection: [],  // 代表勾选的要删除的多个学生数组
                sids: [],                // 要删除的学生编号（可以同时放一个若多个，即可以删除一个或多个学生）
            }
        },
        created() {
            // 1. 查询所有学生
            // this.findStudents()
            // 2. 分页查询所有学生
            // this.findByPage()
            // 3. 查询所有班级
            this.findClasses()
            // 4. 条件查询带分页
            this.search()
        },
        methods: {
            // 1. 用户点击勾选要删除的学生后，得到的multipleSelection数组
            handleSelectionChange(val) {
                this.multipleSelection = val;
                console.log(this.multipleSelection)
            },
            // 1. 保存学生
            save() {
                let url = "/student?cmd=add"        // 默认是添加学生
                //1.1 如果学生存在就是修改操作
                if (this.student.sid) {
                    url = "/student?cmd=update"
                }
                //1.2 保存或修改学生
                studentApi.save(this.student, url).then(({data}) => {
                    this.$message.success(data.message)
                    this.dialogFormVisible = false
                    this.search()
                })
            },
            // 1. 添加学生
            addStud() {
                // 1.1 修改标题
                this.title = "添加学生"
                // 1.2 清空学生对象
                this.student = {}
                // 1.1 显示对话框
                this.dialogFormVisible = true
            },
            //1. 条件查询带分页 (使用async + await 这种es7写法)
            async search() {
                // studentApi.search(this.page, this.pageSize, this.studentSearch).then(({data}) => {
                //     this.studList = data.data.pageResult.list
                //     this.total = data.data.pageResult.total
                // })
                const {data} = await studentApi.search(this.page, this.pageSize, this.studentSearch)
                console.log("data:", data)
                this.studList = data.data.pageResult.list
                this.total = data.data.pageResult.total
            },
            // 2. 查询所有班级
            async findClasses() {
                // classesApi.findClasses().then(({data}) => {
                //     console.log("data:",data)
                //     this.classes = data.data.list
                // })
                const {data} = await classesApi.findClasses()
                this.classes = data.data.list
            },
            // 3. 分页查询所有学生
            findByPage() {
                studentApi.findByPage(this.page, this.pageSize).then(({data}) => {
                    console.log("data:", data)
                    this.studList = data.data.pageResult.list
                    this.total = data.data.pageResult.total
                    console.log(this.total)
                })
            },
            // 4. 每页大小pageSize发生改变时的事件处理函数
            handleSizeChange(pageSize) {
                this.pageSize = pageSize
                // this.findByPage()
                this.search()
                console.log(`每页 ${pageSize} 条`);
            },
            // 5. 每页页码page改变时触发的事件处理函数
            handleCurrentChange(page) {
                this.page = page
                // this.findByPage()
                this.search()
                console.log(`当前页: ${page}`);
            },
            // 6. 查询所有学生
            findStudents() {
                console.log("hello")
                studentApi.findStudents().then(({data}) => {
                    console.log(data)
                    this.studList = data.data.list
                })
            },
            // 7. 编辑
            handleEdit(row) {
                this.title = "修改学生"
                this.student = row
                this.dialogFormVisible = true
            },
            // 8. 删除（单个或批量删除）
            handleDelete(row) {
                // 8.1 如果id有值，说明是删除单个学生
                debugger
                if (row.sid) {                     // 单选
                    this.sids.push(row.sid)
                } else {                      // 多选
                    this.multipleSelection.map(m => {
                        console.log(m)
                        this.sids.push(m.sid)
                    })
                }
                console.log("sids:",this.sids)
                this.$confirm(`你真的要删除学号为${this.sids}`, '温馨提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {     // 点击"确定"按钮时执行的代码
                    //8.2 在后台删除学生
                    const _this = this
                    studentApi.removeStud(this.sids).then(({data}) => {
                        console.log("data:",data)
                        if (data.code === 0) {
                            // this.$message.success(data.message)
                            // this.search()
                            this.$message({
                                type: 'success',
                                message: data.message,
                                onClose() {
                                    _this.search()
                                }
                            });
                        } else {
                            this.$message.error(data.message)
                        }

                    })
                }).catch(() => {    // // 点击"取消"按钮时执行的代码
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
                this.sids = []
            }
        }
    }
</script>
<style>
    #app {
        text-align: center;
    }

    .el-card {
        margin: 0 auto;
        width: 90%;
    }

    .el-pagination {
        margin-top: 20px;
    }
</style>
